/*
 *                        .::::.
 *                      .::::::::.
 *                     :::::::::::
 *                  ..:::::::::::'
 *               '::::::::::::'
 *                 .::::::::::
 *            '::::::::::::::..
 *                 ..::::::::::::.
 *               ``::::::::::::::::
 *                ::::``:::::::::'        .:::.
 *               ::::'   ':::::'       .::::::::.
 *             .::::'      ::::     .:::::::'::::.
 *            .:::'       :::::  .:::::::::' ':::::.
 *           .::'        :::::.:::::::::'      ':::::.
 *          .::'         ::::::::::::::'         ``::::.
 *      ...:::           ::::::::::::'              ``::.
 *     ````':.          ':::::::::'                  ::::..
 *                        '.:::::'                    ':'````..
 *
 * @Author: ls
 * @Date: 2021-03-11 13:52:33
 * @LastEditTime: 2021-03-12 16:26:04
 * @LastEditors: Please set LastEditors
 * @Description: 多语言文本标签
 * @FilePath: \creator_i18n\assets\Script\i18n\i18nLabel.ts
 */

import { i18nMgr } from './i18nMgr';
const { ccclass, property, executeInEditMode, disallowMultiple, requireComponent, menu } = cc._decorator;

@ccclass
@disallowMultiple
@executeInEditMode
@menu('多语言/i18nLabel')
@requireComponent(cc.Label)
export class i18nLabel extends cc.Component {
    @property({ visible: false })
    private i18n_string: string = '';
    @property({ type: cc.String, tooltip: '关键字' })
    get string() {
        return this.i18n_string;
    }
    set string(value: string) {
        this.i18n_string = value;
        this._setLabel();
    }

    @property({ visible: false })
    private i18n_params: string[] = [];
    @property({ type: [cc.String], tooltip: '参数数组' })
    get params() {
        return this.i18n_params;
    }
    set params(value: string[]) {
        this.i18n_params = value;
        this._setLabel();
    }

    start() {
        i18nMgr._addOrDelLabel(this, true);
        this.resetValue();
    }

    onDestroy() {
        i18nMgr._addOrDelLabel(this, false);
    }

    /**
     * 初始化
     * @param string 关键字
     * @param params 参数数组
     */
    public init(string: string, params: string[]) {
        this.i18n_string = string;
        this.i18n_params = params;
        this._setLabel();
    }

    /**
     * 刷新文本值
     */
    public resetValue() {
        this.string = this.i18n_string;
        this.params = this.i18n_params;
    }

    /**
     * 设置文本值
     */
    private _setLabel() {
        let label = this.getComponent(cc.Label);
        if (cc.isValid(label)) {
            label.string = i18nMgr._getLabel(this.i18n_string, this.i18n_params);
        }
    }
}
